package com.demo.netty.handler;

import com.demo.netty.model.ChatMessage;
import com.demo.netty.service.ChatService;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class WebSocketHandler extends SimpleChannelInboundHandler<WebSocketFrame> {
    private static final Logger logger = LoggerFactory.getLogger(WebSocketHandler.class);
    
    @Autowired
    private ChatService chatService;
    
    private final ObjectMapper objectMapper = new ObjectMapper();
    
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame frame) throws Exception {
        if (frame instanceof TextWebSocketFrame) {
            String request = ((TextWebSocketFrame) frame).text();
            logger.info("接收到消息: {}", request);
            
            try {
                ChatMessage message = objectMapper.readValue(request, ChatMessage.class);
                chatService.handleMessage(ctx.channel(), message);
            } catch (Exception e) {
                logger.error("处理消息失败", e);
                ctx.channel().writeAndFlush(new TextWebSocketFrame("消息格式错误"));
            }
        }
    }
    
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        logger.info("新的连接加入: {}", ctx.channel().id().asLongText());
    }
    
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        logger.info("连接断开: {}", ctx.channel().id().asLongText());
        chatService.handleUserDisconnect(ctx.channel());
    }
    
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.error("连接异常", cause);
        ctx.close();
    }
}